// stores/user.js
import { defineStore } from 'pinia'
import api from '@/api'
import router from '@/router'

export const useUserStore = defineStore('user', {
  state: () => ({
    token: localStorage.getItem('token'),
    name: '',
    avatar: '',
    roles: [],
    library_users: {}
  }),

  getters: {
    hasToken: (state) => !!state.token
  },

  actions: {
    // 登录方法
    async login(userInfo) {
      const res = await api.user.login(userInfo)
      console.log(res, '登录成功')
      this.token = res.data.token
      localStorage.setItem('library_token', res.data.token)

      // 添加用户信息获取等待逻辑
      let data = { userId: res.data.id }
      const infoRes = await api.user.getInfo(data)
      
      this.library_users = infoRes.data;
      this.roles = infoRes.data.roles
      localStorage.setItem('library_users', JSON.stringify(infoRes.data))
      
      // 移除这里的 router.push，改由路由守卫统一处理
      return Promise.resolve(res)
    },

    // 登出方法
    async logout() {
      this.$reset()
      localStorage.removeItem('token')
      router.push('/login')
    },

    $reset() { // 自定义重置方法
      this.token = ''
      this.name = ''
      this.avatar = ''
      this.roles = []
    }
  },

  // 开启持久化（需要安装插件 pinia-plugin-persistedstate）
  persist: {
    paths: ['library_token', 'library_users'], // 指定需要持久化的字段
    storage: localStorage // 指定存储方式为 localStorage
  }
})
